from flask import Flask, jsonify, request
import base64
from zhipuai import ZhipuAI
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 启用 CORS 以便前端可以访问后端

# ZhipuAI API Key
API_KEY = "a42450e0bb7df4fa00145471265a7469.h1mURjtbvu7JDVlx"

@app.route('/api/data', methods=['POST'])
def process_image():
    try:
        # 获取前端传入的 JSON 数据
        data = request.json
        img_base64 = data.get('image_base64')

        if not img_base64:
            return jsonify({'status': 'error', 'message': 'No image data provided'}), 400

        # 调用 ZhipuAI API
        client = ZhipuAI(api_key=API_KEY)
        response = client.chat.completions.create(
            model="glm-4v",  # 填写需要调用的模型名称
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": img_base64
                            }
                        },
                        {
                            "type": "text",
                            "text": (
                                "给出题目解答的正确性，并给出详细的解题步骤，并且给出分值，包含每一小问"
                            )
                        }
                    ]
                }
            ]
        )

        # 提取 API 响应内容
        if response and response.choices:
            message = response.choices[0].message.__dict__
        else:
            message = "No response from the API"

        return jsonify({'status': 'success', 'message': message}), 200

    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


if __name__ == '__main__':
    app.run()
